package com.qf.sy2103.homework01.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {


    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<>();

    private static SqlSessionFactory factory ;

    static {

        try {
            final InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    // 事务控制：回滚
    public static void rollbak(){
        SqlSession sqlSession = getSqlSession();
        sqlSession.rollback();
        closeSqlSession();
    }

    // 事务控制：提交
    public static void commit(){
        SqlSession sqlSession = getSqlSession();
        sqlSession.commit();
        closeSqlSession();
    }

    private static void closeSqlSession() {
        final SqlSession sqlSession = threadLocal.get();
        sqlSession.close();
        threadLocal.remove();
    }

    // 获得Mapper对象的方法
    public static <T extends Object> T getMapper(Class<T> clazz){

        SqlSession sqlSession = getSqlSession();

        final T mapper = sqlSession.getMapper(clazz);

        return mapper;
    }

    private static SqlSession getSqlSession() {
        final SqlSession sqlSession = threadLocal.get();

        if (sqlSession!=null){
            return sqlSession;
        }

        final SqlSession session = factory.openSession();

        threadLocal.set(session);

        return session;
    }

}
